import 'dart:convert';

import 'package:cached_network_image/cached_network_image.dart';
import 'package:ecy_app_flutter/routes/group/model/ValleyCircleComment.dart';
import 'package:flutter/material.dart';
import 'package:flutter_easyloading/flutter_easyloading.dart';
import 'package:flutter_screenutil/flutter_screenutil.dart';

import '../../../EcyRouter.dart';
import '../../../ecycommon/EcyCommonWidgets.dart';
import '../../../ecycommon/EcyRequestBaseManager.dart';
import '../../../ecycommon/utils/EcyUserUtil.dart';
import '../../../model/EcyApiCommonResponse.dart';
import '../model/EcyImages.dart';
import '../model/ValleyCirclePost.dart';
import '../model/ValleyCircleReply.dart';
import 'EcyGroupCommentPage.dart';

class EcyGroupDetailPage extends EcyCommonBaseWidget {
  late _EcyGroupDetailPageState state;
  late int id;

  EcyGroupDetailPage({required super.key, required this.id});

  @override
  State<EcyCommonBaseWidget> createState() {
    state = _EcyGroupDetailPageState(id);
    return state;
  }
}

class _EcyGroupDetailPageState extends EcyCommonBaseWidgetState {
  late EcyCommonBaseWidget controller;
  late int id;
  _EcyGroupDetailPageState(this.id);

  final ScrollController _scrollController = ScrollController();
  bool _ownerFlag = false;
  final _talkController = TextEditingController();
  ValleyCirclePost _valleyCirclePost = ValleyCirclePost();
  final List<EcyImages> _ecyImageList = [];

  late EcyGroupCommentPage ecyGroupCommentPage;

  @override
  void initState() {
    super.initState();

    ecyGroupCommentPage = EcyGroupCommentPage(
        key: commentChildKey,
        id: id,
        onPressedCallback: (comment, reply) {
          _showModalBottomSheet(context, comment, reply);
        },
        onCommentDelete: (int deleteCount) {
          if (_valleyCirclePost.commentCount != null) {
            setState(() {
              _valleyCirclePost.commentCount =
                  (_valleyCirclePost.commentCount ?? 1) - deleteCount;
            });
          }
        });

    _scrollController.addListener(_onScroll);

    requestData();
  }

  void _onScroll() {
    if (_scrollController.position.pixels ==
        _scrollController.position.maxScrollExtent) {
      ecyGroupCommentPage.loadData(); // 加载更多数据的函数
    }
  }

  @override
  void dispose() {
    super.dispose();
  }

  @override
  void requestData() async {
    super.requestData();

    Map<String, dynamic> body = {
      "id": id,
    };
    var response = await EcyRequestbasemanager()
        .post("/app/api/app/valley/circle/detail", body);
    if (response != null) {
      var commonResponse =
          EcyApiCommonResponse.fromJson(response, (response) => json);
      if (commonResponse.code == 0 || commonResponse.code == 200) {
        ValleyCirclePost valleyCirclePost =
            ValleyCirclePost.fromJson(response["data"]);
        setState(() {
          _ownerFlag = valleyCirclePost.currentUser == '1';
          _valleyCirclePost = valleyCirclePost;
          _ecyImageList
              .addAll(valleyCirclePost.valleyCirclePostImageList ?? []);
        });
      }
    }
  }

  /// 删除谷圈
  void _deleteGroup(int id) async {
    try {
      var response = await EcyRequestbasemanager()
          .post("/app/api/app/valley/circle/delete", {"id": id});
      EcyApiCommonResponse.fromJson(response, (response) => json);
      Navigator.pop(context, true);
    } catch (e) {
      EasyLoading.showToast("请稍后再试", duration: const Duration(seconds: 2));
    }
  }

  @override
  Widget build(BuildContext context) {
    return Scaffold(
      backgroundColor: Colors.white,
      appBar: AppBar(
        backgroundColor: Colors.white,
        leadingWidth: 50.w,
        scrolledUnderElevation: 0,
        leading: GestureDetector(
          behavior: HitTestBehavior.translucent,
          onTap: () {
            EcyRouter.pop(context, "");
          },
          child: Align(
            alignment: Alignment.centerRight,
            child: Image.asset(
              "assets/images/ic_back.png",
              width: 30.w,
            ),
          ),
        ),
        titleSpacing: 0,
        title: Row(
          mainAxisAlignment: MainAxisAlignment.start,
          children: [
            SizedBox(
              height: 30,
              width: 30,
              child: ClipRRect(
                  borderRadius: BorderRadius.circular(50.0),
                  child: CachedNetworkImage(
                      imageUrl: _valleyCirclePost.userImgUrl ?? "",
                      imageBuilder: (context, imageProvider) => Container(
                            decoration: BoxDecoration(
                                borderRadius: BorderRadius.only(
                                    topRight: Radius.circular(8.r),
                                    topLeft: Radius.circular(8.r)),
                                image: DecorationImage(
                                    image: imageProvider, fit: BoxFit.fill)),
                          ),
                      errorWidget: (context, url, error) =>
                          Image.asset("assets/images/app_icon.png"))),
            ),
            const Padding(padding: EdgeInsets.only(right: 5)),
            Text(
              _valleyCirclePost.userName ?? "",
              style: const TextStyle(fontSize: 16),
            ),
          ],
        ),
        actions: !_ownerFlag
            ? null
            : [
                PopupMenuButton(
                    elevation: 0,
                    offset: const Offset(0, 45),
                    color: Colors.white,
                    shape: RoundedRectangleBorder(
                      borderRadius: BorderRadius.circular(10),
                    ),
                    onSelected: (value) {
                      print(value);
                    },
                    padding: EdgeInsets.zero,
                    menuPadding: EdgeInsets.zero,
                    itemBuilder: (context) => [
                          PopupMenuItem(
                              value: '0',
                              padding: EdgeInsets.zero,
                              child: const Row(
                                mainAxisAlignment: MainAxisAlignment.center,
                                children: [
                                  Image(
                                      image: AssetImage(
                                          'assets/images/ic_edit.png'),
                                      width: 20),
                                  Text('编辑'),
                                ],
                              ),
                              onTap: () async {
                                var logined = await EcyUserUtil.logined();
                                if (logined) {
                                  EcyRouter().push(
                                      context, EcyRouter.groupPublishPage, {
                                    "id": id
                                  }).then((val) => val ? requestData() : null);
                                } else {
                                  EcyRouter.push(
                                      context, EcyRouter.passwordLoginPage, {
                                    EcyRouter.kTargetUrl:
                                        EcyRouter.groupPublishPage
                                  });
                                }
                              }),
                          PopupMenuItem(
                            value: '1',
                            padding: EdgeInsets.zero,
                            child: const Row(
                              mainAxisAlignment: MainAxisAlignment.center,
                              children: [
                                Image(
                                    image: AssetImage(
                                        'assets/images/ic_delete.png'),
                                    width: 20),
                                Text('删除'),
                              ],
                            ),
                            onTap: () async {
                              bool? deleteFlag = await showDeleteConfirmDialog(
                                  '删除后不可恢复，确定删除吗？');
                              if (deleteFlag != null && deleteFlag) {
                                _deleteGroup(_valleyCirclePost.id!);
                              }
                            },
                          ),
                        ],
                    child: const Padding(
                      padding: EdgeInsets.only(right: 10),
                      child: Padding(
                        padding: EdgeInsets.only(bottom: 15),
                        child: Text(
                          "...",
                          style: TextStyle(
                              fontWeight: FontWeight.w600, fontSize: 25),
                        ),
                      ),
                    )),
              ],
      ),
      body: SingleChildScrollView(
        controller: _scrollController,
        physics: const AlwaysScrollableScrollPhysics(),
        child: Container(
          color: Colors.white,
          child: Column(
            crossAxisAlignment: CrossAxisAlignment.start,
            children: [
              SizedBox(
                  height: MediaQuery.of(context).size.width - 20,
                  width: MediaQuery.of(context).size.width,
                  child: PageView(
                    scrollDirection: Axis.horizontal,
                    reverse: false,
                    controller: PageController(
                        initialPage: 1, keepPage: false, viewportFraction: 1),
                    children:
                        (_valleyCirclePost.valleyCirclePostImageList ?? [])
                            .map((e) {
                      return CachedNetworkImage(
                          imageUrl: e.originalUrl ?? "",
                          imageBuilder: (context, imageProvider) => Container(
                                decoration: BoxDecoration(
                                    image: DecorationImage(
                                        image: imageProvider,
                                        fit: BoxFit.contain)),
                              ),
                          errorWidget: (context, url, error) =>
                              Image.asset("assets/images/app_icon.png"));
                    }).toList(),
                  )),
              Padding(
                padding: const EdgeInsets.all(12),
                child: Column(
                    crossAxisAlignment: CrossAxisAlignment.start,
                    children: [
                      Text(_valleyCirclePost.title ?? "",
                          style: const TextStyle(
                            fontFamily: "PingFang SC",
                            fontWeight: FontWeight.w700,
                            fontSize: 16,
                            color: Color(0xFF262626),
                            leadingDistribution:
                                TextLeadingDistribution.even, // 设置leading策略
                          )),
                      const Padding(padding: EdgeInsets.only(bottom: 10)),
                      Text(_valleyCirclePost.content ?? "",
                          style: const TextStyle(
                            fontFamily: "PingFang SC",
                            fontWeight: FontWeight.w500,
                            fontSize: 14,
                            color: Color(0xFF262626),
                            leadingDistribution:
                                TextLeadingDistribution.even, // 设置leading策略
                          )),
                      const Padding(padding: EdgeInsets.only(bottom: 10)),
                      Text(
                          _valleyCirclePost.createTime
                                  ?.replaceFirst("T", " ") ??
                              "",
                          style: const TextStyle(
                            fontFamily: "PingFang SC",
                            fontWeight: FontWeight.w400,
                            fontSize: 12,
                            color: Color(0xFF8C8C8C),
                            leadingDistribution:
                                TextLeadingDistribution.even, // 设置leading策略
                          )),
                      const Padding(padding: EdgeInsets.only(bottom: 20)),
                      Text("评论（${_valleyCirclePost.commentCount ?? 0}）条",
                          style: const TextStyle(
                            fontFamily: "PingFang SC",
                            fontWeight: FontWeight.w700,
                            fontSize: 16,
                            color: Color(0xFF262626),
                            leadingDistribution:
                                TextLeadingDistribution.even, // 设置leading策略
                          )),
                    ]),
              ),
              ecyGroupCommentPage,
            ],
          ),
        ),
      ),
      bottomNavigationBar: BottomAppBar(
        color: Colors.white,
        padding: const EdgeInsets.symmetric(horizontal: 12),
        child: Row(
          // spacing: 10,
          mainAxisAlignment: MainAxisAlignment.spaceAround,
          children: [
            Expanded(
              flex: 3,
              child: GestureDetector(
                onTap: () async {
                  bool logined = await EcyUserUtil.logined();
                  if (logined) {
                    _showModalBottomSheet(context, null, null);
                  } else {
                    EasyLoading.showToast("请先登录",
                        duration: const Duration(seconds: 1));
                  }
                },
                child: Container(
                  decoration: BoxDecoration(
                    borderRadius: BorderRadius.all(Radius.circular(20.r)),
                    color: const Color(0x0A000000), //设置背景色为黑色
                  ),
                  height: 40.w,
                  child: Align(
                      alignment: Alignment.centerLeft,
                      child: Padding(
                        padding: const EdgeInsets.only(left: 20),
                        child: Text(
                          "随便说点什么吧...",
                          style: TextStyle(
                              fontFamily: "PingFang SC",
                              fontWeight: FontWeight.w500,
                              fontSize: 14.sp,
                              color: const Color(0xFFBFBFBF)),
                        ),
                      )),
                ),
              ),
            ),
            Expanded(
              flex: 1,
              child: Padding(
                padding: const EdgeInsets.only(
                  left: 10,
                ),
                child: SizedBox(
                  height: 40.w,
                  child: TextButton(
                      onPressed: () {},
                      style: const ButtonStyle(
                        alignment: Alignment.center,
                        side: WidgetStatePropertyAll(
                            BorderSide(color: Color(0xFFEA4B9B), width: 0.8)),
                        backgroundColor:
                            WidgetStatePropertyAll(Color(0xFFEA4B9B)),
                      ),
                      child: const Text(
                        '发送',
                        style: TextStyle(
                          fontFamily: "PingFang SC",
                          fontWeight: FontWeight.w500,
                          fontSize: 14,
                          color: Color(0xFFFFFFFF),
                          leadingDistribution:
                              TextLeadingDistribution.even, // 设置leading策略
                        ),
                      )),
                ),
              ),
            )
          ],
        ),
      ),
    );
  }

  // 弹出对话框
  Future<bool?> showDeleteConfirmDialog(String content) {
    return showDialog<bool>(
      context: context,
      builder: (context) {
        return AlertDialog(
          // title: const Text(''),
          contentPadding: const EdgeInsets.all(0),
          backgroundColor: Colors.white,
          shape: RoundedRectangleBorder(
            borderRadius: BorderRadius.circular(8.0),
          ),
          content: SizedBox(
            height: 130,
            child: Column(
              mainAxisAlignment: MainAxisAlignment.center,
              children: [
                Padding(
                  padding: const EdgeInsets.only(top: 20, bottom: 30),
                  child: Text(
                    content,
                    style: const TextStyle(fontSize: 18),
                  ),
                ),
                const Divider(height: 0, color: Color(0XFFdcdcdc)),
                SizedBox(
                  height: 50,
                  child: Row(
                    mainAxisAlignment: MainAxisAlignment.center,
                    crossAxisAlignment: CrossAxisAlignment.center,
                    children: <Widget>[
                      Expanded(
                        flex: 1,
                        child: DecoratedBox(
                          decoration: const BoxDecoration(
                              border: Border(
                            right: BorderSide(
                              width: 1.0,
                              color: Color(0XFFdcdcdc),
                            ),
                          )),
                          child: TextButton(
                            style: const ButtonStyle(
                              alignment: Alignment.center,
                            ),
                            child: const Text(
                              '我再想想',
                              style:
                                  TextStyle(fontSize: 18, color: Colors.black),
                            ),
                            onPressed: () =>
                                Navigator.of(context).pop(), // 关闭对话框
                          ),
                        ),
                      ),
                      Expanded(
                        flex: 1,
                        child: TextButton(
                          child: const Text(
                            '确定',
                            style: TextStyle(
                                fontSize: 18, color: Color(0xFFEA4B9B)),
                          ),
                          onPressed: () {
                            //关闭对话框并返回true
                            Navigator.of(context).pop(true);
                          },
                        ),
                      ),
                    ],
                  ),
                ),
              ],
            ),
          ),
          actionsAlignment: MainAxisAlignment.spaceAround,
          actionsPadding: const EdgeInsets.all(0),
        );
      },
    );
  }

  /// 评论
  void _groupComment(
      ValleyCircleComment? commentParent, ValleyCircleReply? reply) async {
    setState(() {
      _valleyCirclePost.commentCount =
          (_valleyCirclePost.commentCount ?? 0) + 1;
    });
    var currUser = await EcyUserUtil.getLoginedUserInfo2();
    bool commentFlag = commentParent == null && reply == null;
    if (commentFlag) {
      ValleyCircleComment valleyCircleComment = ValleyCircleComment();
      valleyCircleComment.postId = id;
      valleyCircleComment.content = _talkController.text;
      valleyCircleComment.userId = currUser.uid;

      try {
        var response = await EcyRequestbasemanager().post(
            "app/api/app/valley/circle/comment", valleyCircleComment.toJson());
        if (response != null) {
          var commonResponse =
              EcyApiCommonResponse.fromJson(response, (response) => json);
          if (commonResponse.code == 0 || commonResponse.code == 200) {
            valleyCircleComment = ValleyCircleComment.fromJson(response["data"]);
            ecyGroupCommentPage.addComment(valleyCircleComment);
            return;
          }
          EasyLoading.showToast("请稍后再试", duration: const Duration(seconds: 2));
        }
      } catch (e) {
        EasyLoading.showToast("请稍后再试", duration: const Duration(seconds: 2));
      }
    } else {
      ValleyCircleReply valleyCircleReply = ValleyCircleReply();
      valleyCircleReply.commentId = commentParent?.id;
      valleyCircleReply.parentReplyId = reply?.id;
      valleyCircleReply.content = _talkController.text;
      valleyCircleReply.toUserId = reply?.userId;
      valleyCircleReply.toUserName = reply?.userName;
      valleyCircleReply.userId = currUser.uid;
      try {
        var response = await EcyRequestbasemanager().post(
            "app/api/app/valley/circle/reply", valleyCircleReply.toJson());
        if (response != null) {
          var commonResponse =
              EcyApiCommonResponse.fromJson(response, (response) => json);
          if (commonResponse.code == 0 || commonResponse.code == 200) {
            valleyCircleReply = ValleyCircleReply.fromJson(response["data"]);
            ecyGroupCommentPage.addReply(commentParent!, valleyCircleReply);
            return;
          }
          EasyLoading.showToast("请稍后再试", duration: const Duration(seconds: 2));
        }
      } catch (e) {
        EasyLoading.showToast("请稍后再试", duration: const Duration(seconds: 2));
      }
    }
  }

  // 评价
  void _showModalBottomSheet(BuildContext context,
      ValleyCircleComment? commentParent, ValleyCircleReply? reply) async {
    _talkController.text = "";
    await showModalBottomSheet(
      isScrollControlled: true,
      isDismissible: true, //点击空白处返回功能，默认是true
      enableDrag: true, //是否允许拖动
      elevation: 10,
      backgroundColor: Colors.white, //背景颜色
      shape: const RoundedRectangleBorder(
        borderRadius: BorderRadius.only(
          topLeft: Radius.circular(10),
          topRight: Radius.circular(10),
        ),
      ), //圆角
      context: context,
      builder: (context) => StatefulBuilder(builder: (context, setState) {
        final keyboardHeight = MediaQuery.of(context).viewInsets.bottom;
        return Padding(
          padding: EdgeInsets.only(bottom: keyboardHeight), //设置底部内边距为软件盘高度
          child: Container(
            constraints: BoxConstraints(
              minHeight: 80, //设置最小高度（必要）
              maxHeight: MediaQuery.of(context).size.height / 1.5, //设置最大高度（必要）
            ),
            padding: const EdgeInsets.only(left: 16, right: 16),
            decoration: BoxDecoration(
              borderRadius: BorderRadius.only(
                topLeft: Radius.circular(30.w),
                topRight: Radius.circular(30.w),
              ),
              color: Colors.white,
            ),
            child: Column(
              mainAxisSize: MainAxisSize.min,
              crossAxisAlignment: CrossAxisAlignment.end,
              children: <Widget>[
                const Padding(padding: EdgeInsets.only(bottom: 20)),
                TextField(
                  autofocus: true,
                  controller: _talkController,
                  cursorColor: const Color(0x73000000),
                  keyboardType: TextInputType.multiline,
                  decoration: InputDecoration(
                    counterText: '',
                    hintText: commentParent == null
                        ? "请说点什么..."
                        : '回复 @${reply?.userName ?? commentParent?.userName}',
                    hintStyle: const TextStyle(color: Color(0x73000000)),
                    filled: true,
                    fillColor: const Color(0x0A000000),
                    border: OutlineInputBorder(
                      borderRadius: BorderRadius.circular(10.0), // 边框圆角
                      borderSide: BorderSide.none,
                    ),
                  ),
                  maxLength: 500,
                  minLines: 2,
                  maxLines: 10,
                ),
                const Padding(padding: EdgeInsets.only(bottom: 20)),
                SizedBox(
                  height: 45.h,
                  width: 100,
                  child: TextButton(
                      onPressed: () {
                        _groupComment(commentParent, reply);
                        Navigator.pop(context, true);
                      },
                      style: const ButtonStyle(
                        alignment: Alignment.center,
                        backgroundColor:
                            WidgetStatePropertyAll(Color(0xFFEA4B9B)),
                        foregroundColor: WidgetStatePropertyAll(Colors.white),
                      ),
                      child: const Text(
                        '发送',
                        style: TextStyle(
                          height: 1,
                          fontSize: 18,
                          leadingDistribution:
                              TextLeadingDistribution.even, // 设置leading策略
                        ),
                      )),
                ),
                const Padding(padding: EdgeInsets.only(bottom: 20)),
              ],
            ),
          ),
        );
      }),
    );
  }
}
